<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryRef"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="竞赛名称" prop="competitionName">
        <el-input
          v-model="queryParams.competitionName"
          placeholder="请输入竞赛名称"
          clearable
          @keyup.enter="handleQuery"
          style="width: 150px"
        />
      </el-form-item>
      <el-form-item label="竞赛级别" prop="competitionLevel">
        <el-select
          v-model="queryParams.competitionLevel"
          placeholder="请选择竞赛级别"
          clearable
          @change="handleQuery"
          style="width: 80px"
        >
          <el-option label="院级" value="院级" />
          <el-option label="校级" value="校级" />
          <el-option label="市级" value="市级" />
          <el-option label="省级" value="省级" />
          <el-option label="国家级" value="国家级" />
        </el-select>
      </el-form-item>
      <el-form-item label="报名开始" prop="registrationStartTime" style="width: 200px">
        <el-date-picker
          clearable
          v-model="queryParams.registrationStartTime"
          type="date"
          value-format="YYYY-MM-DD"
          placeholder="请选择报名开始时间"
        >
        </el-date-picker>
      </el-form-item>
      <el-form-item label="报名结束" prop="registrationEndTime" style="width: 200px">
        <el-date-picker
          clearable
          v-model="queryParams.registrationEndTime"
          type="date"
          value-format="YYYY-MM-DD"
          placeholder="请选择报名结束时间"
        >
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['system:competition:add']"
          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:competition:edit']"
          >修改</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:competition:remove']"
          >删除</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['system:competition:export']"
          >导出</el-button
        >
      </el-col>
      <right-toolbar
        v-model:showSearch="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="competitionList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <!--       <el-table-column label="竞赛记录的唯一标识符" align="center" prop="id" /> -->
      <el-table-column label="竞赛名称" align="center" prop="competitionName" />
      <el-table-column label="竞赛级别" align="center" prop="competitionLevel" />
      <el-table-column label="竞赛形式" align="center" prop="competitionType">
        <template #default="scope">
          <span v-if="scope.row.competitionType === '0'">个人赛</span>
          <span v-else-if="scope.row.competitionType === '1'">团队赛</span>
          <span v-else-if="scope.row.competitionType === '2'">个人赛,团队赛</span>
        </template>
      </el-table-column>
      <!-- <el-table-column label="竞赛描述" align="center" prop="competitionContent" /> -->
      <!-- <el-table-column label="官网地址" align="center" prop="competitionPath" /> -->
      <el-table-column
        label="报名开始时间"
        align="center"
        prop="registrationStartTime"
        width="180"
      >
        <template #default="scope">
          <span>{{ parseTime(scope.row.registrationStartTime, "{y}-{m}-{d}") }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="报名结束时间"
        align="center"
        prop="registrationEndTime"
        width="180"
      >
        <template #default="scope">
          <span>{{ parseTime(scope.row.registrationEndTime, "{y}-{m}-{d}") }}</span>
        </template>
      </el-table-column>
      <!--  <el-table-column label="状态" align="center" prop="status" /> -->
      <!-- <el-table-column label="备注" align="center" prop="remark" /> -->
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button
            link
            type="success"
            icon="Operation"
            @click="handleRaceway(scope.row)"
            >赛道管理</el-button
          >
          <el-button
            link
            type="success"
            icon="Operation"
            @click="handleMember(scope.row)"
            >参赛成员</el-button
          >
        <!--   <el-button
            link
            type="primary"
            icon="Edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:competition:edit']"
            >修改</el-button
          >
          <el-button
            link
            type="primary"
            icon="Delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:competition:remove']"
            >删除</el-button
          > -->
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
    <!-- 添加或修改竞赛对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="competitionRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="竞赛名称" prop="competitionName">
          <el-input v-model="form.competitionName" placeholder="请输入竞赛名称" />
        </el-form-item>
        <el-form-item label="竞赛级别" prop="competitionLevel">
          <el-select
            v-model="competitionLevelArray"
            placeholder="请选择竞赛级别"
            multiple
            collapse-tags
            collapse-tags-tooltip
          >
            <el-option label="国家级" value="国家级" />
            <el-option label="省级" value="省级" />
            <el-option label="市级" value="市级" />
            <el-option label="校级" value="校级" />
            <el-option label="院级" value="院级" />
          </el-select>
        </el-form-item>
        <el-form-item label="竞赛形式" prop="competitionType">
          <el-select v-model="form.competitionType" placeholder="请选择竞赛形式">
            <el-option label="个人赛" value="0" />
            <el-option label="团队赛" value="1" />
            <el-option label="团队赛,个人赛" value="2" />
          </el-select>
        </el-form-item>
        <el-form-item label="竞赛描述">
          <el-input
            v-model="form.competitionContent"
            type="textarea"
            :min-rows="6"
            placeholder="请输入竞赛描述"
          />
        </el-form-item>
        <el-form-item label="官网地址" prop="competitionPath">
          <el-input v-model="form.competitionPath" placeholder="请输入官网地址" />
        </el-form-item>
        <el-form-item label="报名时间" prop="registrationStartTime">
          <el-date-picker
            clearable
            v-model="form.registrationStartTime"
            type="date"
            value-format="YYYY-MM-DD"
            placeholder="请选择报名开始时间"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="结束时间" prop="registrationEndTime">
          <el-date-picker
            clearable
            v-model="form.registrationEndTime"
            type="date"
            value-format="YYYY-MM-DD"
            placeholder="请选择报名结束时间"
          >
          </el-date-picker>
        </el-form-item>
        <!--   <el-form-item label="删除标志" prop="delFlag">
          <el-input v-model="form.delFlag" placeholder="请输入删除标志" />
        </el-form-item> -->
        <el-form-item label="是否禁用" prop="isDisabled">
          <el-input v-model="form.status" placeholder="请输入删除标志(0:否,1:是)" />
        </el-form-item>

        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" placeholder="请输入备注" />
        </el-form-item>
        <el-form-item label="竞赛图片" prop="image">
          <el-upload
            class="avatar-uploader"
            action=""
            :auto-upload="false"
            :on-change="handleImageChange"
            :show-file-list="false"
          >
            <img v-if="form.image" :src="form.image" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>


<script setup name="Competition">
import {
  listCompetition,
  getCompetition,
  delCompetition,
  addCompetition,
  updateCompetition,
} from "@/api/competitionmanagement/competition";
import { uploadImageFile } from "@/api/tool/oss";
import { useRouter } from "vue-router";
import { Plus } from '@element-plus/icons-vue'

const router = useRouter();

const { proxy } = getCurrentInstance();

const competitionList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    competitionName: null,
    competitionLevel: null,
    competitionType: null,
    competitionContent: null,
    competitionPath: null,
    registrationStartTime: null,
    registrationEndTime: null,
    status: null,
    image:null
  },
  rules: {},
  imageFile: null,
});

const { queryParams, form, rules } = toRefs(data);

// 计算属性：处理竞赛级别的数组和字符串转换
const competitionLevelArray = computed({
  get() {
    return form.value.competitionLevel ? form.value.competitionLevel.split(",") : [];
  },
  set(value) {
    form.value.competitionLevel = value.join(",");
  },
});

/** 查询竞赛列表 */
function getList() {
  loading.value = true;
  listCompetition(queryParams.value).then((response) => {
    competitionList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    competitionName: null,
    competitionLevel: null,
    competitionType: null,
    competitionContent: null,
    competitionPath: null,
    registrationStartTime: null,
    registrationEndTime: null,
    status: null,
    delFlag: null,
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null,
    remark: null,
    image: null,
  };
  data.imageFile = null;
  proxy.resetForm("competitionRef");
}

// 处理图片上传
function handleImageChange(file) {
  data.imageFile = file.raw;
  // 创建临时URL用于预览
  form.value.image = URL.createObjectURL(file.raw);
}

// 跳转到参赛人员管理页面
function handleRaceway(row) {
  router.push({
    path: "/competitionmanagement/raceway",
    query: {
      competitionId: row.id,
      competitionName: row.competitionName,
    },
  });
}
function handleMember(row) {
  router.push({
    path: "/competitionmanagement/joined",
    query: {
      competitionName: row.competitionName,
      competitionId: row.id,

    },
  });
}
/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map((item) => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加竞赛";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _id = row.id || ids.value;
  getCompetition(_id).then((response) => {
    form.value = response.data;
    open.value = true;
    title.value = "修改竞赛";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["competitionRef"].validate((valid) => {
    if (valid) {
      proxy.$modal.loading("正在提交中...");
      // 如果有图片文件，先上传图片
      if (data.imageFile) {
        const formData = new FormData();
        formData.append('file', data.imageFile);
        uploadImageFile(data.imageFile).then(response => {
          // 图片上传成功后，将图片URL添加到表单数据中
          form.value.image = response.msg;
          submitCompetitionData();
        }).catch(error => {
          proxy.$modal.closeLoading();
          proxy.$modal.msgError("图片上传失败");
        });
      } else {
        // 没有图片直接提交竞赛数据
        submitCompetitionData();
      }
    }
  });
}

/** 提交竞赛数据 */
function submitCompetitionData() {
  if (form.value.id != null) {
    updateCompetition(form.value)
      .then((response) => {
        proxy.$modal.closeLoading();
        proxy.$modal.msgSuccess("修改成功");
        open.value = false;
        getList();
      })
      .catch(() => { proxy.$modal.closeLoading(); });
  } else {
    addCompetition(form.value)
      .then((response) => {
        proxy.$modal.closeLoading();
        proxy.$modal.msgSuccess("新增成功");
        open.value = false;
        getList();
      })
      .catch(() => { proxy.$modal.closeLoading(); });
  }
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal
    .confirm('是否确认删除竞赛编号为"' + _ids + '"的数据项？')
    .then(function () {
      return delCompetition(_ids);
    })
    .then(() => {
      getList();
      proxy.$modal.msgSuccess("删除成功");
    })
    .catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download(
    "system/competition/export",
    {
      ...queryParams.value,
    },
    `competition_${new Date().getTime()}.xlsx`
  );
}

getList();
</script>

<style scoped>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 120px;
  height: 120px;
  text-align: center;
  display: flex;
  align-items: center;
  justify-content: center;
}

.avatar {
  width: 120px;
  height: 120px;
  display: block;
}
</style>
